const fs =require("fs/file");

let student1 = {
    name: "Alice",
    age: 12,
    scores:[
        {"Chinese":98},
        {"English":120},
        {"Math":135},
        {"History":98},
    ]
};


 let school ={
     schoolName: "希望小学",
     student:[

     ]
 }

/**
 * 在异步回调中为了保证代码的执行顺序我们要将逻辑写在回调函数中*/
fs.readFile("/index.json",(err, data) => {
    if (err) {
        fs.writeFile("./index.json",JSON.stringify(school),err1 => {
            if (err1) throw err1;

            fs.readFile("./index.json",((err1, data1) => {
                if(err1) throw  err1;
                console.log("=================");
                console.log(data1.toString())
                let schoolObj =JSON.parse(data1.toString());
                let studentValue ={};
                studentValue.name=student1.name;
                studentValue.scores =student1.scores;
                schoolObj.student.push(studentValue);

                fs.writeFile("./index.json",JSON.stringify(schoolObj),err1 => {
                    if (err1) throw  err1;
                    console.log("写入成功");
                })
            }))
        })
    }





})
